package net.hserver.sync.event;

import cn.hserver.core.ioc.IocUtil;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.queue.QueueHandler;
import cn.hserver.core.ioc.annotation.queue.QueueListener;
import cn.hserver.core.queue.HServerQueue;
import lombok.extern.slf4j.Slf4j;
import net.hserver.sync.config.EventConst;
import net.hserver.sync.config.LogLevel;
import net.hserver.sync.config.LogType;
import net.hserver.sync.config.FileState;
import net.hserver.sync.driver.WebDavDriver;
import net.hserver.sync.util.PathUtil;

import java.io.FileInputStream;

@Slf4j
@QueueListener(queueName = EventConst.LOCAL_CHANGE_EVENT)
public class LocalChangeEvent {

    @QueueHandler
    public void change(String webDavId, FileState fileState, String localPath, String remotePath) {
        WebDavDriver driver = IocUtil.getBean(webDavId, WebDavDriver.class);
        if (driver == null) {
            return;
        }
        try {
            switch (fileState) {
                case onFileChange, onFileCreate -> {
                    driver.put(remotePath, localPath);
                    HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.FILE_UPLOAD, localPath);
                }
                case onFileDelete -> {
                    driver.delete(remotePath);
                    HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.FILE_DELETE, localPath);
                }
                case onDirectoryCreate -> {
                    driver.mkdirAll(remotePath);
                    HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.DIRECTORY_UPLOAD, localPath);
                    log.info("创建文件夹：{}", remotePath);
                }
                case onDirectoryDelete -> {
                    driver.delete(remotePath);
                    HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.DIRECTORY_DELETE, localPath);
                    log.info("删除文件夹：{}", remotePath);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.ERROR, LogType.OTHER, e.getMessage());
        }
    }

}
